package com.example.sunmiv1.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.example.sunmiv1.entity.ClassificationBean;
import com.example.sunmiv1.entity.ParameterEntity;
import com.example.sunmiv1.room.BaseApp;
import com.example.sunmiv1.utils.net.ACache;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.compile;

/**
 * Created by Administrator on 2018-10-16.
 */

public class Tools {

    /*
     * 將時間戳轉換爲時間
     *
     * s就是時間戳
     */

    public static String stampToDateS(long s, String format) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        //如果它本來就是long類型的,則不用寫這一步
        Date date = new Date(s);
        res = simpleDateFormat.format(date);
        return res;
    }

    public static int dp2px(int value) {
        final float v = BaseApp.INSTANCE.getInstall().getResources().getDisplayMetrics().density;
        return (int) (v * value + 0.5f);
    }


    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }
    //判斷當前字符串是否是商品條碼
    public static boolean isGoodsCode(String str) {
        Pattern pattern = compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            if ("-".equals(splitNotNumber(str))) {
                return true;
            }
            return false;
        }
        return true;
    }
    //判斷當前字符串是否是商品條碼
    public static boolean isAZ(String str) {
        Pattern pattern = compile("[a-zA-Z]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            if ("-".equals(splitNotNumber(str))) {
                return true;
            }
            return false;
        }
        return true;
    }
    // 截取非數字
    public static String splitNotNumber(String content) {
        Pattern pattern = compile("\\D+");
        Matcher matcher = pattern.matcher(content);
        while (matcher.find()) {
            return matcher.group(0);
        }
        return "";
    }


    public static String getPinYinHeadChar(String chines) {
        return ChineseToFirstCharUtil.getChineseInitial(chines);
    }

    public static long getStringToDate(String dateString) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        try {
            date = dateFormat.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date.getTime();
    }

    public static Bitmap getCode(String content, int width, int height) {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Map<EncodeHintType, String> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        try {
            BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            int[] pixels = new int[width * height];
            for (int i = 0; i < height; i++) {
                for (int j = 0; j < width; j++) {
                    if (encode.get(j, i)) {
                        pixels[i * width + j] = 0x00000000;
                    } else {
                        pixels[i * width + j] = 0xffffffff;
                    }
                }
            }
            return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 92      * 獲取屏幕高度
     * 93      *
     * 94      * @param context
     * 95
     */
    public static int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        return wm.getDefaultDisplay().getHeight();
    }


    /**
     * 設置輸入框只能輸入兩位小數點
     *
     * @param edit
     */
    public static void setEdit(final EditText edit) {
        edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.toString().contains(".")) {
                    if (charSequence.length() - 1 - charSequence.toString().indexOf(".") > 2) {
                        charSequence = charSequence.toString().subSequence(0, charSequence.toString().indexOf(".") + 3);
                        edit.setText(charSequence);
                        edit.setSelection(charSequence.length());
                    }
                }
                if (charSequence.toString().trim().substring(0).equals(".")) {
                    charSequence = "0" + charSequence;
                    edit.setText(charSequence);
                    edit.setSelection(2);
                }

                if (charSequence.toString().startsWith("0") && charSequence.toString().trim().length() > 1) {
                    if (!charSequence.toString().substring(1, 2).equals(".")) {
                        edit.setText(charSequence.subSequence(1, 2));
                        edit.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    /**
     * @return String 生成32位的隨機數作爲id
     */
    public static String getCode() {
        //Random rd = new Random();
        String str = "";
        for (int i = 0; i < 32; i++) {
            // 你想生成幾個字符的，就把9改成幾，如果改成１,那就生成一個隨機字母．
            str = str + (char) (Math.random() * 26 + 'a');
        }
        return str;
    }

    /**
     * 生成祕鑰
     *
     * @param jsonObject 要加密的參數
     * @return
     */
    private static ACache aCache;
    private static SharedPreferences sp;

    public static JSONObject createParameterCode(JSONObject jsonObject) {
        aCache = ACache.get(BaseApp.INSTANCE.getInstall());
        sp = BaseApp.INSTANCE.getInstall().getSharedPreferences("context", Activity.MODE_PRIVATE);//創建sp對象
        try {
            String store_id = aCache.getAsString("storeid");
            String merchant_id = aCache.getAsString("merchantid");
            String cashier_id = aCache.getAsString("uid");
            jsonObject.put("store_id", TextUtils.isEmpty(store_id) ? sp.getString("store_id", "") : store_id);
            jsonObject.put("merchant_id", TextUtils.isEmpty(merchant_id) ? sp.getString("merchant_id", "") : merchant_id);
            jsonObject.put("storeid", TextUtils.isEmpty(store_id) ? sp.getString("store_id", "") : store_id);
            jsonObject.put("merchantid", TextUtils.isEmpty(merchant_id) ? sp.getString("merchant_id", "") : merchant_id);
            if(!jsonObject.has("user_type")) {
                jsonObject.put("user_type", aCache.getAsString("userType"));
            }
            if ("2".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("operator_id"));
            } else if ("1".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            }else{
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            }
            if("3".equals(aCache.getAsString("userType"))) {
                jsonObject.put("cashier_id", TextUtils.isEmpty(cashier_id) ? sp.getString("cashier_id", "") : cashier_id);
            }
            Iterator<String> iterator = jsonObject.keys();
            List<ParameterEntity> parameterEntityList = new ArrayList<>();
            String url = "";
            String sign = "";
            while (iterator.hasNext()) {
                try {
                    String key = "";
                    ParameterEntity parameterEntity = new ParameterEntity();
                    key = iterator.next();
                    parameterEntity.setKey(key);
                    parameterEntity.setValue(jsonObject.get(key));
                    parameterEntityList.add(parameterEntity);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            printParameterEntity(parameterEntityList);
            sortEntity(parameterEntityList);
            printParameterEntity(parameterEntityList);
            url = parseToUrl(parameterEntityList);
//            Log.e(TAG, "createParameterCode: url=" + url);
            sign = md5(url);
//            Log.e(TAG, "createParameterCode: sign1=" + sign);
            sign = sign.toUpperCase();
//            Log.e(TAG, "createParameterCode: sign2=" + sign);
            jsonObject.put("sign", sign);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * 數組排序
     *
     * @param parameterEntityList 待排序數組
     */
    public static void sortEntity(List<ParameterEntity> parameterEntityList) {
        for (int i = 0; i < parameterEntityList.size() - 1; i++) {
            for (int j = i + 1; j < parameterEntityList.size(); j++) {
                if (parameterEntityList.get(i).getKey().compareTo(parameterEntityList.get(j).getKey()) > 0) {
                    swap(parameterEntityList, i, j);
                }
            }
        }
    }

    /**
     * 交換數組位置
     *
     * @param parameterEntityList 待交換數組
     * @param i                   交換位置1
     * @param j                   交換位置2
     */
    public static void swap(List<ParameterEntity> parameterEntityList, int i, int j) {
        ParameterEntity parameterEntity_i = new ParameterEntity();
        parameterEntity_i.setKey(parameterEntityList.get(i).getKey());
        parameterEntity_i.setValue(parameterEntityList.get(i).getValue());
        ParameterEntity parameterEntity_j = new ParameterEntity();
        parameterEntity_j.setKey(parameterEntityList.get(j).getKey());
        parameterEntity_j.setValue(parameterEntityList.get(j).getValue());
        parameterEntityList.get(i).setKey(parameterEntity_j.getKey());
        parameterEntityList.get(i).setValue(parameterEntity_j.getValue());
        parameterEntityList.get(j).setKey(parameterEntity_i.getKey());
        parameterEntityList.get(j).setValue(parameterEntity_i.getValue());
    }

    /**
     * 裝換成url參數
     *
     * @param parameterEntityList 轉換的數組
     * @return
     */
    public static String parseToUrl(List<ParameterEntity> parameterEntityList) {
        aCache = ACache.get(BaseApp.INSTANCE.getInstall());
        String url = "";
        for (int i = 0; i < parameterEntityList.size(); i++) {
            url = url + parameterEntityList.get(i).getKey() + "=" + parameterEntityList.get(i).getValue();
            if (parameterEntityList.size() != i + 1) {
                url = url + "&";
            }
        }
        url = url + "&key=" + aCache.getAsString("login_key");
        return url;
    }

    /**
     * md5加密
     *
     * @param string 要加密的字符串
     * @return
     */
    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes()); //獲取二進制
            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result.append(temp);
            }
            return result.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    private static final String TAG = "Tools";

    /**
     * 打印數組數據
     *
     * @param parameterEntityList
     */
    public static void printParameterEntity(List<ParameterEntity> parameterEntityList) {
        for (int i = 0; i < parameterEntityList.size(); i++) {
//            Log.e(TAG, "printParameterEntity: i=" + i);
//            Log.e(TAG, "printParameterEntity: key+value=" + parameterEntityList.get(i).getKey() + "+" + parameterEntityList.get(i).getValue());
        }
    }

    /**
     * 獲取當前時間
     */
    public static String getNowTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = simpleDateFormat.format(new Date());
        return dateString;
    }


    /**
     * 點擊某個textView，調起時間選擇器，設置該時間選擇器返回的時間給該textView
     *
     * @param tv textView
     */
    public static void getDateFromDatePickerDialog(TextView tv) {
        Calendar calendar = Calendar.getInstance();
        new DatePickerDialog(tv.getContext(), AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
            // 綁定監聽器(How the parent is notified that the date is set.)
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // 此處得到選擇的時間，可以進行你想要的操作
                if ((monthOfYear + 1) < 10) {
                    if (dayOfMonth < 10) {
                        tv.setText(year + "-0" + (monthOfYear + 1) + "-0" + dayOfMonth);
                    } else {
                        tv.setText(year + "-0" + (monthOfYear + 1) + "-" + dayOfMonth);
                    }
                } else {
                    if (dayOfMonth < 10) {
                        tv.setText(year + "-" + (monthOfYear + 1) + "-0" + dayOfMonth);
                    } else {
                        tv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                    }
                }
            }
        }// 設置初始日期
                , calendar.get(Calendar.YEAR)
                , calendar.get(Calendar.MONTH)
                , calendar.get(Calendar.DAY_OF_MONTH)).show();
    }

    /**
     * 點擊某個textView，調起時間選擇器，設置該時間選擇器返回的時間給該textView
     *
     * @param tv textView
     */
    public static void getDateFromDatePickerDialog(TextView tv,TimeCallback timeCallback) {
        Calendar calendar = Calendar.getInstance();
        // 綁定監聽器(How the parent is notified that the date is set.)
        new DatePickerDialog(tv.getContext(), AlertDialog.THEME_HOLO_LIGHT, (view, year, monthOfYear, dayOfMonth) -> {
            // 此處得到選擇的時間，可以進行你想要的操作
            if ((monthOfYear + 1) < 10) {
                if (dayOfMonth < 10) {
                    tv.setText(year + "-0" + (monthOfYear + 1) + "-0" + dayOfMonth);
                    timeCallback.time(year + "-0" + (monthOfYear + 1) + "-0" + dayOfMonth);
                } else {
                    tv.setText(year + "-0" + (monthOfYear + 1) + "-" + dayOfMonth);
                    timeCallback.time(year + "-0" + (monthOfYear + 1) + "-" + dayOfMonth);
                }
            } else {
                if (dayOfMonth < 10) {
                    tv.setText(year + "-" + (monthOfYear + 1) + "-0" + dayOfMonth);
                    timeCallback.time(year + "-" + (monthOfYear + 1) + "-0" + dayOfMonth);
                } else {
                    tv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                    timeCallback.time(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                }
            }
        }// 設置初始日期
                , calendar.get(Calendar.YEAR)
                , calendar.get(Calendar.MONTH)
                , calendar.get(Calendar.DAY_OF_MONTH)).show();
    }

    public interface TimeCallback{
        void time(String time);
    }

    /**
     * 彈出選擇器  三級列表封裝
     *
     * @param mContext           activity
     * @param tvPickSort         分類textview
     * @param options1Items      一級列表
     * @param options2Items      二級列表
     * @param options3Items      三級列表
     * @param classificationBean 分類對應bean
     *                           <p>
     *                           return   category  各分類列表對應id
     */
    public static String[] showPickerView(Context mContext, TextView tvPickSort, List<String> options1Items,
                                          List<List<String>> options2Items,
                                          List<List<List<String>>> options3Items,
                                          ClassificationBean classificationBean) {
        String[] categorys = {"", "", ""}; //各分類列表對應id
        OptionsPickerView pvOptions = new OptionsPickerBuilder(mContext, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分別是三個級別的選中位置
                String opt1tx, opt2tx, opt3tx;
                Arrays.fill(categorys, "");

                opt1tx = options1Items.size() > 0 ?
                        options1Items.get(options1) : "";
                categorys[0] = options1Items.size() > 0 ? classificationBean.getGoodscate().get(options1).getId() : "";


                opt2tx = options2Items.get(options1).get(options2);
                if (classificationBean.getGoodscate().size() > 0
                        && classificationBean.getGoodscate().get(options1).getChild().size() > 0)
                    categorys[1] = classificationBean.getGoodscate().get(options1).getChild().get(options2).getId() == null ? "" : classificationBean.getGoodscate().get(options1).getChild().get(options2).getId();


                opt3tx = options3Items.get(options1).get(options2).get(options3);
                if (classificationBean.getGoodscate().size() > 0
                        && classificationBean.getGoodscate().get(options1).getChild().size() > 0
                        && classificationBean.getGoodscate().get(options1).getChild().get(options2).getChild().size() > 0)
                    categorys[2] = classificationBean.getGoodscate().get(options1).getChild().get(options2).getChild().get(options3).getId() == null ? "" : classificationBean.getGoodscate().get(options1).getChild().get(options2).getChild().get(options3).getId();


                opt1tx = opt1tx.length() > 3 ? opt1tx.substring(0, 3) + ".." : opt1tx;
                opt2tx = opt2tx.length() > 3 ? opt2tx.substring(0, 3) + ".." : opt2tx;
                opt3tx = opt3tx.length() > 3 ? opt3tx.substring(0, 3) + ".." : opt3tx;

                String tx = opt1tx;
                if (opt2tx != null) {
                    tx = opt1tx + ">" + opt2tx;
                } else if (opt3tx != null) {
                    tx = opt1tx + ">" + opt2tx + ">" + opt3tx;
                }
                tvPickSort.setText(tx);

            }
        })
                .setTitleText("")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //設置選中項文字顏色
                .setContentTextSize(14)
                .build();
        /*pvOptions.setPicker(options1Items);//一級選擇器*/
//        pvOptions.setPicker(options1Items, options2Items);//二級選擇器
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三級選擇器
        pvOptions.show();
        return categorys;
    }

    /**
     * 通過判斷字段是否爲空來讓view所在的ViewGroup隱藏或者顯示
     *
     * @param beansParam java bean中的字段
     * @param view       可能需要隱藏的view
     */
    public static void hideViewInItem(String beansParam, TextView view) {
        if (TextUtils.isEmpty(beansParam)) {
            View v = (View) view.getParent();
            v.setVisibility(View.GONE);
        } else {
            View v = (View) view.getParent();
            v.setVisibility(View.VISIBLE);
            view.setText(beansParam);
        }
    }

    /**
     * 給editText，添加監聽並防止數據渲染混亂
     *
     * @param beansParam java bean中的字段
     * @param et         editText
     */
    public static void setEditText(Class clazz, String beansParam, EditText et) {
        Field[] allFields = clazz.getDeclaredFields();
        for (Field field : allFields) {
            if (beansParam.equals(field.getName())) {

            }
        }
        et.setText(beansParam);
        et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
//                mList.get(position).setRemarks(s.toString());
            }
        });
    }

}
